package com.ndp.fb.scheduler.configwatch;

import com.ndp.fb.config.ConfigCentre;
import com.ndp.fb.constant.ConfigConst;
import com.ndp.fb.dubbo.container.ConfigWatcher;
import com.ndp.fb.scheduler.annotation.CronScheduledAnnoationBeanPostProcessor;
import com.ndp.fb.scheduler.annotation.ScheduleLock;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Map;

/**
 * Created by hunk.qin on 2015/3/20.
 */
@Component
public class SchedulerConfigWatcher implements ConfigWatcher {

    protected final Log logger = LogFactory.getLog(SchedulerConfigWatcher.class);


    @Autowired
    public CronScheduledAnnoationBeanPostProcessor cronScheduledAnnoationBeanPostProcessor;

    @Autowired
    private ScheduleLock scheduleLock;
    @Override
    public synchronized void notification(ApplicationContext applicationContext, String appId, Map<String, String> configmap) {
        if(appId.contains(ConfigConst.SCHEDULER_SERVICES_ID)){
            if(scheduleLock.haslock){
                logger.info("scheduled 配置改变了,重新初始化调度任务，重新注册任务~！！！");
                cronScheduledAnnoationBeanPostProcessor.reRegisterDestroy();
                for (Object o : cronScheduledAnnoationBeanPostProcessor.objectmap.values()) {
                    cronScheduledAnnoationBeanPostProcessor.getObject(o,o.getClass().getName());
                }
                cronScheduledAnnoationBeanPostProcessor.reRegister();

                //logger
                //LoggerConfigWatcher.singleton().resetLog(configmap);
            }else{
                logger.info("当前节点没有获得调度锁，不能进行重新注册~！！！");
            }
        }
    }

    @PostConstruct
    public void registWatcher(){
        ConfigCentre.addWatcher(this);
    }

}
